﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Memcached.ClientLibrary;
using System.Collections;

namespace Emoney.UserTraining.Cache
{
    public class News2CacheTools : IMemcachedCache
    {
        static string cacheName = Guid.NewGuid().ToString();
        static News2CacheTools()
        {
            String[] serverlist = System.Configuration.ConfigurationManager.AppSettings["Memcached"].Split(',', '|');
            SockIOPool pool = SockIOPool.GetInstance(cacheName);
            pool.SetServers(serverlist);
            pool.Initialize();
        }

        private string GetKey(string key)
        {
            return "UserTraining" + key;
        }

        public object GetClient()
        {
            MemcachedClient mc = new MemcachedClient();
            mc.PoolName = cacheName;
            mc.EnableCompression = false;
            return mc;
        }

        public object [] GetMultiple(List<string> keys)
        {
            if(keys==null || keys.Count==0)
            {
                return new object[0];
            }
            for (int i = 0; i < keys.Count; i++)
            {
                keys[i] = GetKey(keys[i]);
            }
            MemcachedClient cache = (MemcachedClient)GetClient();
            return cache.GetMultipleArray(keys.ToArray());
        }
 
        public T Get<T>(string key)
        {
            try
            {
                key = GetKey(key);
                MemcachedClient cache = (MemcachedClient)GetClient();

                return (T)cache.Get(key);
            }
            catch
            {
                return default(T);
            }
        }


        public void Add(string key, object obj, int hours, int minutes, int seconds)
        {
            key = GetKey(key);
            MemcachedClient cache = (MemcachedClient)GetClient();
            if (!cache.Add(key, obj, DateTime.Now.Add(new TimeSpan(hours, minutes, seconds))))
            { 
                cache.Set(key, obj, DateTime.Now.Add(new TimeSpan(hours, minutes, seconds)));
            }
        }

        public void Remove(string key)
        {
            key = GetKey(key);
            MemcachedClient cache = (MemcachedClient)GetClient();
            cache.Delete(key);
        }

        public void FlushAll()
        {
            throw new NotImplementedException();
        }
    }
}
